<!--
 * @Author: zi.yang
 * @Date: 2021-03-12 19:43:22
 * @LastEditors: zi.yang
 * @LastEditTime: 2021-03-13 00:01:28
 * @Description: In User Settings Edit
 * @FilePath: \vue-music\src\components\state3\test-watch.vue
-->

<template>
  <div>
    <div>
      点击次数 ：{{ count }} --- 动画特效
      <span v-bind:class="{ spin: isClass }" style="color:red">
        {{ watch_count && isClass ? '停止触发' : '允许触发' }}
      </span>
    </div>
    <button @click="add()">click Me to Trigger animation</button>
    <button @click="handleClick()">handleClick</button>
  </div>
</template>

<script>
import {
  reactive, toRef, toRefs, watchEffect, watch,
} from '@vue/composition-api';

export default {
  name: 'test-watch',
  setup() {
    const state = reactive({
      count: 0,
      watch_count: 0,
      isClass: true,
      add() {
        if (this.watch_count === 1) {
          return;
        }
        this.isClass = true;
        this.count += 1;
        this.watch_count = 1;
        const timer = setTimeout(() => {
          this.isClass = false;
          this.watch_count = 0;
          clearTimeout(timer);
        }, 1700);
      },
      handleClick() {
        this.count += 1;
      },
    });

    // 副作用，监听
    const stop = watchEffect(() => {
      // watchEffect 会监听 state.count
      if (state.count) {
        console.log(new Date());
      }
      if (state.count === 5) {
        console.log('停止监听 count');
        stop();
      }
    });

    watchEffect(async (cancel) => {
      const promise = await new Promise((resolve, reject) => {
        // 2. 紧接着触发
        console.log(state.count);
        resolve(state.count);
        reject(new Error('触发失败'));
      });

      // 3.最后触发
      console.log(`輸出：${promise}`);

      // 会在异步之前触发，清除副作用
      cancel(() => {
        // 1. 首先触发
        console.log('cancel');
      });
    });

    // watch 指定监听某一个属性
    // 注：当前测试效果，并没有发现监听触发
    watch(toRef(state.count), (thatCount, prevCoount) => {
      console.log(`${thatCount}-----${prevCoount}`);
    });

    return toRefs(state);
  },
};
</script>

<style scoped>
.spin {
  font-size: 18px;
  animation: 1.5s spin;
}

button {
  margin: 10px;
  border: 0px;
  height: inherit;
  width: 220px;
  color: #333;
  font-size: 18px;
  font-weight: small;
  padding: 9px;
  border-radius: 7px;
  background: orange;
  transition: all .4s linear;
}

button:hover {
  color: red;
  transform: scale(1.1);
}

@keyframes spin {
  50% {
    font-size: 26px;
    color: greenyellow;
    transform: rotate(60deg);
  }
  100% {
    color: aqua;
    font-size: 18px;
    transform: rotate(0deg);
  }
}
</style>
